import * as turf from "@turf/turf";
import { Map } from "mapbox-gl";
import Base from "./Base";
// @ts-ignore
import wkt from "terraformer-wkt-parser";
import { ILayerProps } from "src/types/index";
export default class AreaLayer extends Base {
  layerId: string;
  layerIdLine: string;
  constructor(map: Map, layerProps: ILayerProps) {
    let SOURCE_NAME = "AreaLayer";
    super(map, layerProps, SOURCE_NAME);

    this.layerId = this.getLayerName("default")
    this.layerIdLine = this.getLayerName("line");

    this.init();
  }

  init() {
    this.map.addSource(this.sourceId, {
      type: "geojson",
      data: turf.featureCollection(this.features) as any,
    });

    //区域边线
    this.map.addLayer({
      id: this.layerIdLine,
      type: "line",
      source: this.sourceId,
      layout: {
        "line-join": "round",
        "line-cap": "square",
      },
      paint: {
        "line-color": "rgba(255,255,255,1)",
        "line-opacity": 0.5,
        "line-width": 3,
        /*'line-blur': 1,
                    'line-dasharray': [4, 3]*/
      },
    });

    //区域背景
    this.map.addLayer({
      id: this.layerId,
      type: "fill",
      source: this.sourceId,
      minzoom: 0,
      maxzoom: 15,
      paint: {
        "fill-color": [
          "match",
          ["get", "colorindex"],
          5,
          "rgba(221, 17, 26,.9)",
          4,
          "rgba(224, 125, 40,.9)",
          3,
          "rgba(232, 212, 55,.9)",
          2,
          "rgba(121, 233, 133,.9)",
          1,
          "rgba(52, 150, 254,.6)",
          0,
          "rgba(255, 255, 255,0)",
          "rgba(255, 255, 255,0)",
        ],
        "fill-outline-color": "white",
      },
      //'filter': ['>', 'colorlevel', 0]
    });
  }

  formatChildrenList<T>(children: T[] = [], propertiesCallback?: (v: any) => any, geometryKey = "GEOMETRY") {
    let datas = [];
    for (let i = 0; i < children.length; i++) {
      // @ts-ignore
      if (children[i][geometryKey]) {
        // @ts-ignore
        let geometry = wkt.parse(children[i][geometryKey]);
        if (geometry.type == "Point") {
          let point = turf.point(geometry.coordinates);
          // @ts-ignore
          let buffered = turf.buffer(point, 10, { units: "meters" });
          geometry = buffered.geometry;
        }
        datas.push({
          type: "Feature",
          geometry,
          properties:
            typeof propertiesCallback !== "function"
              ? {}
              : propertiesCallback(children[i]),
        });
      }
    }
    return datas;
  }
}
